<template>
  <div class="online-practice-view">
    <!-- 练习设置页面 -->
    <div v-if="!practiceStarted" class="practice-setup">
      <div class="setup-container">
        <h1 class="page-title">在线练习</h1>
        <p class="page-subtitle">选择练习类型和题目数量，开始你的学习之旅</p>
        
        <div class="setup-form">
          <el-card class="setup-card">
            <h3 class="card-title">练习设置</h3>
            
            <el-form :model="practiceConfig" label-width="120px" class="practice-form">
              <el-form-item label="题目分类">
                <el-select v-model="practiceConfig.categoryId" placeholder="选择分类" clearable>
                  <el-option
                    v-for="category in categories"
                    :key="category.id"
                    :label="category.name"
                    :value="category.id"
                  />
                </el-select>
              </el-form-item>
              
              <el-form-item label="题目难度">
                <el-select v-model="practiceConfig.difficulty" placeholder="选择难度" clearable>
                  <el-option label="简单" :value="1" />
                  <el-option label="中等" :value="2" />
                  <el-option label="困难" :value="3" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="题目类型" required>
                <el-select v-model="practiceConfig.type" placeholder="请选择题目类型" clearable>
                  <el-option label="单选题" value="single" />
                  <el-option label="简答题" value="short" />
                </el-select>
                <div class="form-tip">考公题目主要为单选题和简答题</div>
              </el-form-item>
              
              <el-form-item label="题目数量">
                <el-input-number
                  v-model="practiceConfig.count"
                  :min="5"
                  :max="50"
                  :step="5"
                  controls-position="right"
                />
                <span class="form-tip">建议选择10-30道题目</span>
              </el-form-item>
              
              <el-form-item label="时间限制">
                <el-switch v-model="practiceConfig.timeLimit" />
                <span class="form-tip">开启后将限制总答题时间</span>
              </el-form-item>
              
              <el-form-item v-if="practiceConfig.timeLimit" label="限制时间">
                <el-input-number
                  v-model="practiceConfig.timeLimitMinutes"
                  :min="5"
                  :max="120"
                  :step="5"
                  controls-position="right"
                />
                <span class="form-tip">分钟</span>
              </el-form-item>
            </el-form>
            
            <div class="setup-actions">
              <el-button type="primary" size="large" @click="startPractice" :loading="loading">
                开始练习
              </el-button>
              <el-button @click="resetConfig">重置设置</el-button>
            </div>
          </el-card>
          
          <!-- 练习历史 -->
          <el-card class="history-card">
            <h3 class="card-title">最近练习</h3>
            <div class="history-list" v-if="practiceHistory.length > 0">
              <div v-for="item in practiceHistory" :key="item.id" class="history-item">
                <div class="history-info">
                  <h4>{{ item.categoryName }}</h4>
                  <p>{{ item.totalCount }}道题 · {{ formatTime(item.timeSpent) }} · {{ item.score }}分</p>
                </div>
                <div class="history-score" :class="getScoreClass(item.score)">
                  {{ item.score }}分
                </div>
              </div>
            </div>
            <el-empty v-else description="暂无练习记录" />
          </el-card>
        </div>
      </div>
    </div>

    <!-- 练习进行中 -->
    <div v-else-if="practiceStarted && !practiceFinished" class="practice-active">
      <div class="practice-header">
        <div class="practice-info">
          <h2>正在练习</h2>
          <p>第 {{ currentQuestionIndex + 1 }} 题 / 共 {{ questions?.length || 0 }} 题</p>
        </div>
        <div class="practice-timer">
          <el-icon><Clock /></el-icon>
          <span>{{ formatTime(remainingTime) }}</span>
        </div>
        <el-button type="danger" @click="endPractice">结束练习</el-button>
      </div>
      
      <div class="practice-progress">
        <el-progress 
          :percentage="Math.round((currentQuestionIndex / (questions?.length || 1)) * 100)"
          :stroke-width="8"
        />
      </div>
      
      <div class="question-container">
        <div class="question-card">
          <div class="question-header">
            <div class="question-meta">
              <el-tag :type="getDifficultyType(currentQuestion.difficulty)">
                {{ getDifficultyText(currentQuestion.difficulty) }}
              </el-tag>
              <el-tag type="info">{{ currentQuestion.type }}</el-tag>
            </div>
            <div class="question-number">第 {{ currentQuestionIndex + 1 }} 题</div>
          </div>
          
          <div class="question-content">
            <h3 class="question-title">{{ currentQuestion.title || currentQuestion.content }}</h3>
            <div class="question-description" v-if="currentQuestion.description">
              <p>{{ currentQuestion.description }}</p>
            </div>
            <div class="question-image" v-if="currentQuestion.imageUrl">
              <img 
                :src="currentQuestion.imageUrl" 
                :alt="'题目图片'"
                @error="handleImageError"
                class="question-img"
              />
            </div>
          </div>
          
          <!-- 选择题选项 -->
          <div v-if="currentQuestion.type === 'SINGLE_CHOICE' || currentQuestion.type === 'MULTIPLE_CHOICE' || currentQuestion.type === 'TRUE_FALSE'" class="question-options">
            <!-- 调试信息 -->
            <div v-if="!currentQuestion.options || currentQuestion.options.length === 0" class="debug-info" style="color: red; padding: 10px; background: #ffe6e6; border: 1px solid #ff9999; margin: 10px 0;">
              <strong>调试信息：</strong> 题目 {{ currentQuestionIndex + 1 }} 没有选项数据！
              <br>题目ID: {{ currentQuestion.id }}
              <br>题目类型: {{ currentQuestion.type }}
              <br>选项数组: {{ currentQuestion.options }}
            </div>
            
            <div 
              v-for="(option, index) in currentQuestion.options" 
              :key="option.id"
              class="option-item"
              :class="{ 
                'selected': isOptionSelected(option.id),
                'multiple-selected': currentQuestion.type === 'MULTIPLE_CHOICE' && isOptionSelected(option.id)
              }"
              @click="selectOption(index)"
            >
              <div class="option-label">{{ String.fromCharCode(65 + index) }}</div>
              <div class="option-content">{{ option.content }}</div>
              <div v-if="currentQuestion.type === 'MULTIPLE_CHOICE' && isOptionSelected(option.id)" class="option-check">
                ✓
              </div>
            </div>
          </div>
          
          <!-- 填空题输入框 -->
          <div v-else-if="currentQuestion.type === 'FILL_BLANK'" class="question-input">
            <el-input
              v-model="fillBlankAnswer"
              type="textarea"
              :rows="4"
              placeholder="请输入您的答案..."
              class="fill-blank-input"
            />
          </div>
          
          <!-- 简答题输入框 -->
          <div v-else-if="currentQuestion.type === 'SHORT_ANSWER'" class="question-input">
            <el-input
              v-model="shortAnswerAnswer"
              type="textarea"
              :rows="6"
              placeholder="请简要回答（建议200-500字）..."
              class="short-answer-input"
            />
          </div>
          
          <!-- 论述题输入框 -->
          <div v-else-if="currentQuestion.type === 'ESSAY'" class="question-input">
            <el-input
              v-model="essayAnswer"
              type="textarea"
              :rows="12"
              placeholder="请根据题目要求撰写文章（建议800字以上）..."
              class="essay-input"
            />
            <div class="word-count" :class="getWordCountClass()">
              字数统计：{{ essayAnswer.length }} 字
            </div>
          </div>
          
          <div class="question-actions">
            <el-button 
              v-if="currentQuestionIndex > 0"
              @click="previousQuestion"
            >
              上一题
            </el-button>
            <el-button 
              type="primary"
              @click="nextQuestion"
              :disabled="!hasAnswerForCurrentQuestion()"
            >
              {{ currentQuestionIndex === questions.length - 1 ? '完成练习' : '下一题' }}
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 练习结果 -->
    <div v-else-if="practiceFinished" class="practice-result">
      <div class="result-container">
        <div class="result-header">
          <h1 class="result-title">练习完成！</h1>
          <p class="result-subtitle">恭喜你完成了本次练习</p>
        </div>
        
        <div class="result-summary">
          <div class="summary-card">
            <div class="summary-item">
              <div class="summary-value">{{ result.score }}</div>
              <div class="summary-label">总分</div>
            </div>
            <div class="summary-item">
              <div class="summary-value">{{ result.correctCount }}/{{ result.totalCount }}</div>
              <div class="summary-label">正确题数</div>
            </div>
            <div class="summary-item">
              <div class="summary-value">{{ Math.round((result.correctCount / result.totalCount) * 100) }}%</div>
              <div class="summary-label">正确率</div>
            </div>
            <div class="summary-item">
              <div class="summary-value">{{ formatTime(result.timeSpent) }}</div>
              <div class="summary-label">用时</div>
            </div>
          </div>
        </div>
        
        <div class="result-analysis">
          <h3>答题分析</h3>
          <div class="analysis-list">
            <div 
              v-for="(item, index) in result.analysis" 
              :key="item.questionId"
              class="analysis-item"
              :class="{ 'correct': item.isCorrect, 'incorrect': !item.isCorrect }"
            >
              <div class="analysis-header">
                <span class="question-num">第 {{ index + 1 }} 题</span>
                <el-tag :type="item.isCorrect ? 'success' : 'danger'">
                  {{ item.isCorrect ? '正确' : '错误' }}
                </el-tag>
              </div>
              <div class="analysis-content">
                <p><strong>你的答案：</strong>{{ formatAnswer(item.userAnswer) }}</p>
                <p><strong>正确答案：</strong>{{ formatAnswer(item.correctAnswer) }}</p>
                <p><strong>解析：</strong>{{ item.explanation }}</p>
              </div>
            </div>
          </div>
        </div>
        
        <div class="result-actions">
          <el-button type="primary" @click="restartPractice">重新练习</el-button>
          <el-button @click="backToSetup">返回设置</el-button>
          <el-button @click="viewWrongQuestions">查看错题</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Clock } from '@element-plus/icons-vue'
import { getQuestionCategories, getPracticeQuestions, submitPracticeAnswers, getPracticeHistory } from '@/api/question'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const practiceStarted = ref(false)
const practiceFinished = ref(false)
const currentQuestionIndex = ref(0)
const remainingTime = ref(0)
const timer = ref<NodeJS.Timeout | null>(null)
const startTime = ref<Date | null>(null)
const questionStartTime = ref<Date | null>(null)

// 练习配置
const practiceConfig = ref({
  categoryId: null as number | null,
  difficulty: null as number | null,
  type: null as string | null,
  count: 20,
  timeLimit: false,
  timeLimitMinutes: 30
})

// 数据
const categories = ref<any[]>([])
const questions = ref<any[]>([])
const userAnswers = ref<(number | number[] | string)[]>([])
const practiceHistory = ref<any[]>([])
const result = ref<any>({})

// 文本输入答案
const fillBlankAnswer = ref('')
const shortAnswerAnswer = ref('')
const essayAnswer = ref('')

// 计算属性
const currentQuestion = computed(() => {
  return questions.value[currentQuestionIndex.value] || {}
})

// 方法
const loadCategories = async () => {
  try {
    const response = await getQuestionCategories()
    categories.value = response
  } catch (error) {
    console.error('加载分类失败', error)
    // 使用默认分类
    categories.value = [
      { id: 1, name: '言语理解与表达' },
      { id: 2, name: '数量关系' },
      { id: 3, name: '判断推理' },
      { id: 4, name: '资料分析' },
      { id: 5, name: '常识判断' }
    ]
  }
}

const loadPracticeHistory = async () => {
  try {
    const response = await getPracticeHistory({ page: 1, pageSize: 5 })
    practiceHistory.value = response.list || []
  } catch (error) {
    console.error('加载练习历史失败', error)
  }
}

const startPractice = async () => {
  if (!practiceConfig.value.count) {
    ElMessage.warning('请选择题目数量')
    return
  }
  
  if (!practiceConfig.value.type) {
    ElMessage.warning('请选择题目类型')
    return
  }
  
  try {
    loading.value = true
    
    // 调试信息
    console.log('=== 开始练习调试信息 ===')
    console.log('用户选择的类型:', practiceConfig.value.type)
    console.log('映射后的类型:', mapTypeToBackend(practiceConfig.value.type))
    console.log('题目数量:', practiceConfig.value.count)
    console.log('分类ID:', practiceConfig.value.categoryId)
    console.log('难度:', practiceConfig.value.difficulty)
    
    // 获取题目
    const questionsData = await getPracticeQuestions({
      categoryId: practiceConfig.value.categoryId || undefined,
      difficulty: practiceConfig.value.difficulty || undefined,
      type: mapTypeToBackend(practiceConfig.value.type),
      count: practiceConfig.value.count
    })
    
    console.log('后端返回的题目数量:', questionsData.length)
    console.log('后端返回的题目类型分布:')
    questionsData.forEach((q, index) => {
      console.log(`题目${index + 1}: ID=${q.id}, 类型=${q.type}, 内容=${q.content?.substring(0, 50)}...`)
    })
    
    if (questionsData.length === 0) {
      ElMessage.warning('没有找到符合条件的题目')
      return
    }
    
    questions.value = questionsData
    userAnswers.value = new Array(questionsData.length).fill(undefined)
    practiceStarted.value = true
    practiceFinished.value = false
    currentQuestionIndex.value = 0
    
    // 记录开始时间
    startTime.value = new Date()
    questionStartTime.value = new Date()
    
    // 设置计时器
    if (practiceConfig.value.timeLimit) {
      remainingTime.value = practiceConfig.value.timeLimitMinutes * 60
      startTimer()
    }
    
    ElMessage.success('练习开始！')
    
  } catch (error) {
    console.error('开始练习失败', error)
    ElMessage.error('开始练习失败')
  } finally {
    loading.value = false
  }
}

const startTimer = () => {
  timer.value = setInterval(() => {
    remainingTime.value--
    if (remainingTime.value <= 0) {
      endPractice()
    }
  }, 1000)
}

const stopTimer = () => {
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }
}

const isOptionSelected = (optionId: number) => {
  const currentAnswer = userAnswers.value[currentQuestionIndex.value]
  if (currentQuestion.value.type === 'SINGLE_CHOICE') {
    return currentAnswer === optionId
  } else if (currentQuestion.value.type === 'MULTIPLE_CHOICE') {
    return Array.isArray(currentAnswer) && currentAnswer.includes(optionId)
  }
  return false
}

const hasAnswerForCurrentQuestion = () => {
  const currentAnswer = userAnswers.value[currentQuestionIndex.value]
  if (currentQuestion.value.type === 'SINGLE_CHOICE') {
    return currentAnswer !== undefined && currentAnswer !== null
  } else if (currentQuestion.value.type === 'MULTIPLE_CHOICE') {
    return Array.isArray(currentAnswer) && currentAnswer.length > 0
  } else if (currentQuestion.value.type === 'FILL_BLANK') {
    return fillBlankAnswer.value.trim().length > 0
  } else if (currentQuestion.value.type === 'SHORT_ANSWER') {
    return shortAnswerAnswer.value.trim().length > 0
  } else if (currentQuestion.value.type === 'ESSAY') {
    return essayAnswer.value.trim().length > 0
  }
  return false
}

const selectOption = (index: number) => {
  const currentQuestion = questions.value[currentQuestionIndex.value]
  if (currentQuestion.type === 'SINGLE_CHOICE') {
    // 单选题：存储选项ID
    userAnswers.value[currentQuestionIndex.value] = currentQuestion.options[index].id
  } else if (currentQuestion.type === 'MULTIPLE_CHOICE') {
    // 多选题：存储选项ID数组
    if (!userAnswers.value[currentQuestionIndex.value]) {
      userAnswers.value[currentQuestionIndex.value] = []
    }
    const currentAnswers = userAnswers.value[currentQuestionIndex.value] as number[]
    const optionId = currentQuestion.options[index].id
    
    if (currentAnswers.includes(optionId)) {
      // 如果已选择，则取消选择
      const indexToRemove = currentAnswers.indexOf(optionId)
      currentAnswers.splice(indexToRemove, 1)
    } else {
      // 如果未选择，则添加
      currentAnswers.push(optionId)
    }
  }
}

// 保存当前题目的文本输入答案
const saveCurrentTextAnswer = () => {
  const currentQuestion = questions.value[currentQuestionIndex.value]
  if (currentQuestion.type === 'FILL_BLANK') {
    userAnswers.value[currentQuestionIndex.value] = fillBlankAnswer.value
  } else if (currentQuestion.type === 'SHORT_ANSWER') {
    userAnswers.value[currentQuestionIndex.value] = shortAnswerAnswer.value
  } else if (currentQuestion.type === 'ESSAY') {
    userAnswers.value[currentQuestionIndex.value] = essayAnswer.value
  }
}

// 恢复当前题目的文本输入答案
const restoreTextAnswer = () => {
  const currentQuestion = questions.value[currentQuestionIndex.value]
  const savedAnswer = userAnswers.value[currentQuestionIndex.value]
  
  if (currentQuestion.type === 'FILL_BLANK') {
    fillBlankAnswer.value = typeof savedAnswer === 'string' ? savedAnswer : ''
  } else if (currentQuestion.type === 'SHORT_ANSWER') {
    shortAnswerAnswer.value = typeof savedAnswer === 'string' ? savedAnswer : ''
  } else if (currentQuestion.type === 'ESSAY') {
    essayAnswer.value = typeof savedAnswer === 'string' ? savedAnswer : ''
  }
}

// 获取字数统计的样式类
const getWordCountClass = () => {
  const wordCount = essayAnswer.value.length
  if (wordCount >= 800) {
    return 'success'
  } else if (wordCount >= 600) {
    return 'warning'
  } else {
    return 'error'
  }
}

const nextQuestion = async () => {
  // 保存当前题目的文本输入答案
  saveCurrentTextAnswer()
  
  if (currentQuestionIndex.value === questions.value.length - 1) {
    // 最后一题，提交答案
    await submitAnswers()
  } else {
    currentQuestionIndex.value++
    // 记录下一题的开始时间
    questionStartTime.value = new Date()
    // 恢复下一题的文本输入答案
    restoreTextAnswer()
  }
}

const previousQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    // 保存当前题目的文本输入答案
    saveCurrentTextAnswer()
    
    currentQuestionIndex.value--
    
    // 恢复上一题的文本输入答案
    restoreTextAnswer()
  }
}

const submitAnswers = async () => {
  try {
    loading.value = true
    
    // 计算总用时（秒）
    const endTime = new Date()
    const totalTimeSpent = startTime.value ? 
      Math.floor((endTime.getTime() - startTime.value.getTime()) / 1000) : 0
    
    // 计算每题的用时（平均分配）
    const averageTimePerQuestion = questions.value.length > 0 ? 
      Math.floor(totalTimeSpent / questions.value.length) : 0
    
    const answers = questions.value.map((question, index) => {
      let answer = userAnswers.value[index] || null
      
      // 处理不同类型的答案
      if (question.type === 'SINGLE_CHOICE' || question.type === 'MULTIPLE_CHOICE') {
        // 选择题：answer 已经是选项ID或ID数组，直接使用
        answer = userAnswers.value[index] || null
      } else if (question.type === 'FILL_BLANK') {
        answer = fillBlankAnswer.value || ''
      } else if (question.type === 'SHORT_ANSWER') {
        answer = shortAnswerAnswer.value || ''
      } else if (question.type === 'ESSAY') {
        answer = essayAnswer.value || ''
      }
      
      // 确保答案不为空，如果为空则使用默认值
      if (answer === null || answer === undefined) {
        if (question.type === 'SINGLE_CHOICE' || question.type === 'MULTIPLE_CHOICE') {
          answer = question.type === 'SINGLE_CHOICE' ? 0 : []
        } else {
          answer = ''
        }
      }
      
      console.log(`题目${index + 1} (ID=${question.id}) 答案:`, answer)
      
      return {
        questionId: question.id,
        answer: answer,
        timeSpent: averageTimePerQuestion
      }
    })
    
    const response = await submitPracticeAnswers({
      practiceId: `practice_${Date.now()}`,
      answers,
      timeSpent: totalTimeSpent
    })
    
    result.value = response
    practiceFinished.value = true
    stopTimer()
    
    ElMessage.success('练习完成！')
    
  } catch (error) {
    console.error('提交答案失败', error)
    ElMessage.error('提交答案失败')
  } finally {
    loading.value = false
  }
}

const endPractice = async () => {
  try {
    await ElMessageBox.confirm('确定要结束练习吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 保存当前题目的答案
    saveCurrentTextAnswer()
    
    // 提交答案
    await submitAnswers()
  } catch (error) {
    // 用户取消操作
    console.log('用户取消结束练习')
  }
}

const restartPractice = () => {
  practiceStarted.value = false
  practiceFinished.value = false
  currentQuestionIndex.value = 0
  questions.value = []
  userAnswers.value = []
  result.value = {}
  startTime.value = null
  questionStartTime.value = null
  stopTimer()
  
  // 清空文本输入
  fillBlankAnswer.value = ''
  shortAnswerAnswer.value = ''
  essayAnswer.value = ''
}

const backToSetup = () => {
  restartPractice()
}

const viewWrongQuestions = () => {
  // 跳转到错题页面
  router.push('/error-question')
}

const resetConfig = () => {
  practiceConfig.value = {
    categoryId: null,
    difficulty: null,
    type: null,
    count: 20,
    timeLimit: false,
    timeLimitMinutes: 30
  }
}

const getDifficultyType = (difficulty: number) => {
  if (difficulty <= 3) return 'success'
  if (difficulty <= 6) return 'warning'
  return 'danger'
}

const getDifficultyText = (difficulty: number) => {
  if (difficulty <= 3) return '简单'
  if (difficulty <= 6) return '中等'
  return '困难'
}

const getScoreClass = (score: number) => {
  if (score >= 80) return 'excellent'
  if (score >= 60) return 'good'
  return 'poor'
}

const formatTime = (seconds: number) => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}

const mapTypeToBackend = (type: string) => {
  const typeMap: Record<string, string> = {
    'single': 'SINGLE_CHOICE',
    'short': 'SHORT_ANSWER'
  }
  return typeMap[type] || 'SINGLE_CHOICE'
}

const formatAnswer = (answer: any) => {
  if (typeof answer === 'number') {
    return String.fromCharCode(65 + answer)
  }
  if (Array.isArray(answer)) {
    return answer.map(a => String.fromCharCode(65 + a)).join(', ')
  }
  return answer || '未作答'
}

const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.style.display = 'none'
  console.warn('图片加载失败:', img.src)
}

// 组件挂载
onMounted(() => {
  loadCategories()
  loadPracticeHistory()
})

// 组件卸载
onUnmounted(() => {
  stopTimer()
})
</script>

<style lang="scss" scoped>
.online-practice-view {
  min-height: 100vh;
  background: #f5f7fa;
}

.practice-setup {
  padding: 40px 20px;
  
  .setup-container {
    max-width: 1000px;
    margin: 0 auto;
  }
  
  .page-title {
    font-size: 2.5rem;
    font-weight: 700;
    text-align: center;
    margin-bottom: 10px;
    color: #1f2937;
  }
  
  .page-subtitle {
    font-size: 1.2rem;
    text-align: center;
    color: #6b7280;
    margin-bottom: 40px;
  }
  
  .setup-form {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 30px;
    
    @media (max-width: 768px) {
      grid-template-columns: 1fr;
    }
  }
  
  .setup-card, .history-card {
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    
    .card-title {
      font-size: 1.5rem;
      font-weight: 600;
      margin-bottom: 20px;
      color: #1f2937;
    }
  }
  
  .practice-form {
    .form-tip {
      font-size: 12px;
      color: #9ca3af;
      margin-left: 10px;
    }
  }
  
  .setup-actions {
    display: flex;
    gap: 15px;
    justify-content: center;
    margin-top: 30px;
  }
  
  .history-list {
    .history-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px;
      border: 1px solid #e5e7eb;
      border-radius: 8px;
      margin-bottom: 10px;
      
      .history-info {
        h4 {
          margin: 0 0 5px 0;
          font-size: 14px;
          color: #1f2937;
        }
        
        p {
          margin: 0;
          font-size: 12px;
          color: #6b7280;
        }
      }
      
      .history-score {
        font-weight: 600;
        font-size: 16px;
        
        &.excellent {
          color: #10b981;
        }
        
        &.good {
          color: #f59e0b;
        }
        
        &.poor {
          color: #ef4444;
        }
      }
    }
  }
}

.practice-active {
  padding: 20px;
  
  .practice-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: white;
    padding: 20px;
    border-radius: 12px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    
    .practice-info {
      h2 {
        margin: 0 0 5px 0;
        color: #1f2937;
      }
      
      p {
        margin: 0;
        color: #6b7280;
      }
    }
    
    .practice-timer {
      display: flex;
      align-items: center;
      gap: 5px;
      font-size: 18px;
      font-weight: 600;
      color: #ef4444;
    }
  }
  
  .practice-progress {
    margin-bottom: 30px;
  }
  
  .question-container {
    max-width: 800px;
    margin: 0 auto;
    
    .question-card {
      background: white;
      border-radius: 12px;
      padding: 30px;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
      
      .question-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        
        .question-meta {
          display: flex;
          gap: 10px;
        }
        
        .question-number {
          font-weight: 600;
          color: #6b7280;
        }
      }
      
      .question-content {
        margin-bottom: 30px;
        
        .question-title {
          font-size: 18px;
          font-weight: 600;
          color: #1f2937;
          margin: 0 0 15px 0;
          line-height: 1.5;
        }
        
        .question-description {
          p {
            color: #6b7280;
            line-height: 1.6;
            margin: 0;
          }
        }
        
        .question-image {
          margin: 20px 0;
          text-align: center;
          
          .question-img {
            max-width: 100%;
            max-height: 400px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            object-fit: contain;
          }
        }
      }
      
      .question-options {
        margin-bottom: 30px;
        
        .option-item {
          display: flex;
          align-items: center;
          gap: 15px;
          padding: 15px;
          border: 2px solid #e5e7eb;
          border-radius: 8px;
          margin-bottom: 10px;
          cursor: pointer;
          transition: all 0.2s;
          
          &:hover {
            border-color: #3b82f6;
          }
          
          &.selected {
            border-color: #3b82f6;
            background-color: #eff6ff;
          }
          
          .option-label {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background-color: #f3f4f6;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            color: #6b7280;
            flex-shrink: 0;
          }
          
          .option-content {
            flex: 1;
            color: #1f2937;
          }
        }
      }
      
      .question-actions {
        display: flex;
        justify-content: space-between;
      }
    }
  }
}

.practice-result {
  padding: 40px 20px;
  
  .result-container {
    max-width: 1000px;
    margin: 0 auto;
  }
  
  .result-header {
    text-align: center;
    margin-bottom: 40px;
    
    .result-title {
      font-size: 2.5rem;
      font-weight: 700;
      color: #1f2937;
      margin: 0 0 10px 0;
    }
    
    .result-subtitle {
      font-size: 1.2rem;
      color: #6b7280;
      margin: 0;
    }
  }
  
  .result-summary {
    margin-bottom: 40px;
    
    .summary-card {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 20px;
      background: white;
      padding: 30px;
      border-radius: 12px;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
      
      @media (max-width: 768px) {
        grid-template-columns: repeat(2, 1fr);
      }
      
      .summary-item {
        text-align: center;
        
        .summary-value {
          font-size: 2rem;
          font-weight: 700;
          color: #1f2937;
          margin-bottom: 5px;
        }
        
        .summary-label {
          font-size: 14px;
          color: #6b7280;
        }
      }
    }
  }
  
  .result-analysis {
    background: white;
    border-radius: 12px;
    padding: 30px;
    margin-bottom: 30px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    
    h3 {
      font-size: 1.5rem;
      font-weight: 600;
      color: #1f2937;
      margin: 0 0 20px 0;
    }
    
    .analysis-list {
      .analysis-item {
        padding: 20px;
        border: 1px solid #e5e7eb;
        border-radius: 8px;
        margin-bottom: 15px;
        
        &.correct {
          border-color: #10b981;
          background-color: #f0fdf4;
        }
        
        &.incorrect {
          border-color: #ef4444;
          background-color: #fef2f2;
        }
        
        .analysis-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 10px;
          
          .question-num {
            font-weight: 600;
            color: #1f2937;
          }
        }
        
        .analysis-content {
          p {
            margin: 5px 0;
            color: #6b7280;
            line-height: 1.5;
          }
        }
      }
    }
  }
  
  .result-actions {
    display: flex;
    gap: 15px;
    justify-content: center;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .practice-active {
    .practice-header {
      flex-direction: column;
      gap: 15px;
      text-align: center;
    }
    
  .question-container {
    .question-card {
      padding: 20px;
    }
  }
  
  // 文本输入框样式
  .question-input {
    margin: 20px 0;
    
    .fill-blank-input,
    .short-answer-input,
    .essay-input {
      width: 100%;
      
      :deep(.el-textarea__inner) {
        border-radius: 8px;
        border: 2px solid #e5e7eb;
        font-size: 16px;
        line-height: 1.6;
        padding: 16px;
        transition: all 0.3s ease;
        
        &:focus {
          border-color: #3b82f6;
          box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }
        
        &::placeholder {
          color: #9ca3af;
          font-style: italic;
        }
      }
    }
    
    .essay-input {
      :deep(.el-textarea__inner) {
        min-height: 300px;
        font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
      }
    }
    
    .word-count {
      text-align: right;
      margin-top: 8px;
      font-size: 14px;
      color: #6b7280;
      
      &.success {
        color: #10b981;
        font-weight: 600;
      }
      
      &.warning {
        color: #f59e0b;
      }
      
      &.error {
        color: #ef4444;
      }
    }
  }
}
}
</style>
